/*
 * @(#)WorkflowActionTakerTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.taglib;

import java.sql.Connection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.WebUtil;
import com.dcivision.workflow.bean.MtmWorkflowDynamicUserActor;
import com.dcivision.workflow.bean.MtmWorkflowProgressUserRecord;
import com.dcivision.workflow.bean.MtmWorkflowStepUserActor;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.core.WorkflowRetrievalManager;
import com.dcivision.workflow.dao.MtmWorkflowDynamicUserActorDAObject;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;

/**
 * @author           Tony Chen
 * @company          DCIVision Limited
 * @creation date    13/10/2005
 * @version          $Revision: 1.3.4.2 $
 */
public class WorkflowActionTakerTag extends WorkflowStepOwnerTag {
  public static final String REVISION = "$Revision: 1.3.4.2 $";

  protected Log log = LogFactory.getLog(this.getClass().getName());  
 
  private String assignedTo = null;
  
  
  
	public String getAssignedTo() {
		return assignedTo;
	}
  
	public void setAssignedTo(String assignedTo) {
		this.assignedTo = assignedTo;
	}
  
  public WorkflowActionTakerTag() {
    super();
  }
  
  public void release() {
    super.release();    
  }

  protected boolean validateTag(){
    return ( this.getWorkflowProgress()!=null );
  }

  protected String getContent() throws ApplicationException {
    StringBuffer sb = new StringBuffer();
    Connection conn = null;
    try {
      conn = (Connection) pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
      //display assigned to
      if (GlobalConstant.TRUE.equals(this.assignedTo)) {
        sb.append(this.getAssignedToUser(conn));
      
      //display action taker
      } else {
      	//if the progress status is pending, then get the owner.
      	if (WorkflowProgress.STATUS_PENDING.equals(this.getWorkflowProgress().getStatus())) {
      		sb.append(this.getAssignedToUser(conn));
      		
      		//if the progress status is not pending, then get the action taker
      	} else {
      		
      		WorkflowRetrievalManager retrievalManager = new WorkflowRetrievalManager(sessionContainer, conn);
      		List userActionList = retrievalManager.getWorkflowProgressUserRecordListByProgressID( this.getWorkflowProgress().getID());
      		for (int j = 0; j < userActionList.size(); j++) {
      			MtmWorkflowProgressUserRecord wfProgressUserRecord = (MtmWorkflowProgressUserRecord)userActionList.get(j);
      			if (j > 0) {
      				sb.append("<br>");  
      			}
      			sb.append("<img src=\'" + WebUtil.getImage(pageContext.getRequest(), "IconUser.gif")+"\' align=\'absmiddle\' border=\'0\'>" + wfProgressUserRecord.getUserRecordName());          
      		}
      		
      	}
      }
    
    } catch(Exception ex){
      conn = null;        
    } finally {
      conn = null;
    }


    return sb.toString();
  }


  protected String getFilterByDescription() throws ApplicationException {
  	if ( Utility.isEmpty(super.getFilterBy())){
  		return "";
  	}
  	StringBuffer sbFilter = new StringBuffer();
  	sbFilter.append("<br><b><u style=\'font-size:11px\'>");
  	sbFilter.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "workflow.label.filter_by"));
  	sbFilter.append(":</u></b><br>");
  	sbFilter.append(super.getFilterByDescription());
  	log.debug(sbFilter.toString());
  	return sbFilter.toString();
  }
  
  protected void init() throws ApplicationException {
    if ( !validateTag() ){
      throw new IllegalArgumentException();
    }

    if ( this.getWorkflowProgress()==null ){
      Connection conn = (Connection) pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
      WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(sessionContainer, conn);

      if ( this.getWorkflowProgress() == null ) {
       this.setWorkflowProgress((WorkflowProgress) progressDAO.getObjectByID(this.getWorkflowProgress().getID()));
      }
    } else if ( this.getWorkflowProgress().getUserActorList()!=null ){
      super.setUserActorList(this.getWorkflowProgress().getUserActorList());
      super.setFilterBy(null);
    }
    super.setStepID(this.getWorkflowProgress().getWorkflowStepID());
    super.init();
  }
  
  private String getAssignedToUser(Connection conn) throws ApplicationException {
    StringBuffer sb = new StringBuffer();
    //check if is dynamic assign owner in this progress
    boolean isDynamicAssignOwner = false;
    List userActorList = this.getWorkflowProgress().getUserActorList();
    for (int i = 0; i < userActorList.size(); i++) {
      MtmWorkflowStepUserActor wfStepUserActor = (MtmWorkflowStepUserActor)userActorList.get(i);
      if (MtmWorkflowStepUserActor.ACTOR_TYPE_RUNTIME_ASSIGN.equals(wfStepUserActor.getActorType())) {
        isDynamicAssignOwner = true;
        break;
      }
    }
    
    MtmWorkflowDynamicUserActorDAObject dynamicDAO = new MtmWorkflowDynamicUserActorDAObject(sessionContainer, conn);
    List dynamicActorList = dynamicDAO.getListByWorkflowProgressID(this.getWorkflowProgress().getID());
        
    //if is dynamic assign ower in the progress, then display the dynamic assign ower
    if (isDynamicAssignOwner && !Utility.isEmpty(dynamicActorList)) {      
      String iconName = null;
      
      if (!GlobalConstant.TRUE.equals(this.assignedTo)) {
        sb.append("<b><u style=\'font-size:11px\'>");
        sb.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "workflow.label.assigned_to"));
        sb.append(":</u></b><br>");
      }      
      
      for (int i = 0; i < dynamicActorList.size(); i++) {
        MtmWorkflowDynamicUserActor dynamicActor = (MtmWorkflowDynamicUserActor) dynamicActorList.get(i);
        //user
        if (MtmWorkflowStepUserActor.ACTOR_TYPE_USER.equals(dynamicActor.getActorType())) {
          iconName = "IconUser.gif";              
          
        //user group  
        } else if (MtmWorkflowStepUserActor.ACTOR_TYPE_GROUP.equals(dynamicActor.getActorType())) {
          iconName = "IconGroup.gif";  
          
        //user role  
        } else if (MtmWorkflowStepUserActor.ACTOR_TYPE_ROLE.equals(dynamicActor.getActorType())) {
          iconName = "IconRole.gif";  
        }
        
        if (i > 0) {
          sb.append("<br>");
        }
        sb.append("<img src=\'" + WebUtil.getImage(pageContext.getRequest(), iconName) + "\' align=\'absmiddle\' border=\'0\'>" + dynamicActor.getActorName() + "[" + dynamicActor.getPermission() + "]");
      }
      
      
    //display the assign ower  
    } else {
      this.setRight("R");
      this.setObjectType(GlobalConstant.WORKFLOW_OWNER_PERMISSION);
      this.setObjectID(this.getWorkflowProgress().getWorkflowStepID());
      //if has permission or this step is dynamic assign owner and not assign user yet.
      if (this.checkPermission() || (isDynamicAssignOwner && Utility.isEmpty(dynamicActorList)) ) {
        sb.append (getActorNameDescription());
        sb.append (getFilterByDescription());
      }
    }               
    
    return sb.toString();
  }
}

